package com.fhyc.intercepter;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fhyc.util.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


@Slf4j
@Component
//创建拦截器
public class LoginInterceptor implements HandlerInterceptor {

    private Set<String> whitelist = new HashSet<>();

    // 在构造函数中读取配置文件，初始化白名单
    public LoginInterceptor() {
        loadWhitelistFromConfig();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws JsonProcessingException {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        // 检查请求路径是否在白名单中
        if (whitelist.contains(requestURI)) {
            return true;  // 放行请求
        }

        boolean isValid = validateRequest(request); // 自定义验证逻辑

        if (isValid) {
            // 如果验证不通过，可以直接返回错误响应或重定向等操作
            //response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return true;
        }

        // 验证通过，可以放行请求继续处理
        //return false;
        return true;
    }

    private boolean validateRequest(HttpServletRequest request) throws JsonProcessingException {
        // 实现自定义的请求验证逻辑，例如检查请求参数、权限等
        String accessToken = "";
        if (StringUtils.isNotEmpty(request.getHeader("accessToken"))){
            accessToken    = request.getHeader("accessToken");
        }else {
           accessToken = request.getHeader("Access-Token");
        }
        if (accessToken != null && !"".equals(accessToken) && !"null".equals(accessToken)) {
            String strTokenclaims = accessToken.split("\\.")[1];
            String strCalimsJson = Base64Util.decodeToString(strTokenclaims);
            ObjectMapper objMapper = new ObjectMapper();
            Map map = objMapper.readValue(strCalimsJson, Map.class);
            String userId = map.get("userId").toString();
            Long refreshDate = (Long) map.get("refreshDate");
            if (StringUtils.isNotEmpty(userId) && refreshDate>0){
                return true;
            }
        }
         // 根据具体逻辑返回验证结果
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }


    // 从配置文件加载白名单信息
    private void loadWhitelistFromConfig() {
        // 实现从配置文件中读取白名单信息的逻辑
        whitelist.add("/api/fm/login/verify");  // 登录接口路径
        whitelist.add("/api/fm/");
    }

}
